import React from "react";

import { addon, Ref, getObject, log, PermissionState } from "pao-aop";

import { reactControl, ReactViewControl, ReactView, ReactViewState, CommonIcon } from "pao-aop-client";
import { StatisticalAnalysisLayout } from "src/projects/industryInternetSign/components/statistical-analysis-layout";
// import ReactEcharts from "echarts-for-react";
// import { singleRectangularCoordinateOptionAssign } from "src/business/components/echarts-react/option";
import { AnalysisStatistics, StatisticsData, IAnalysisStatisticsService } from "src/models/analysisStatistics";

import { NTOperationTable } from "src/business/components/operation-table";
import { NTButtonSelect } from "src/business/components/button-select";
import { NTButtonOption } from "src/business/components/button-option";
import { EchartsReact } from "src/business/components/echarts-react";
import { Tooltip, notification, Spin, Icon } from "antd";
import { lineOption, barOption } from "./option";
import { IndustryInternetSignAppStorage } from "../../app/appStorage";
import { PermissionList } from "../../app/permission";
import { ROUTE_PATH, isPermission } from "../../app/util-tool";

const columns_data_source = [{
    title: '排名',
    key: 'ranking',
    render: (text: string, record: any, index: number) => `${index + 1}`,
    width: 80
}, {
    title: '标识名称',
    dataIndex: 'name',
    key: 'name',
    width: 200
}, {
    title: '标识码',
    dataIndex: 'handle_name',
    key: 'handle_name',
    width: 200
}, {
    title: '解析数量',
    dataIndex: 'count',
    key: 'count',
    width: 120
}];
/**
 * 组件：统计分析视图控件状态
 */
export interface StatisticalAnalysisViewState extends ReactViewState {
    /** 企业模板标识折线图 */
    company_model_line_data?: any[];
    /** 品类模板标识折线图 */
    category_model_line_data?: any[];
    /** 单品标识折线图 */
    single_product_model_line_data?: any[];
    /** 外链标识折线图 */
    external_links_model_line_data?: any[];
    /** 总解析折线图 */
    total_analysis_line?: any[];
    /** 标识解析排行榜数据集合 */
    ranking_list_data?: AnalysisStatistics[];
    /** 标识解析统计数据 */
    statistics_data?: StatisticsData;
    /** 滚动条 */
    loading?: boolean;
}

/**
 * 组件：统计分析视图控件
 */
export class StatisticalAnalysisView extends ReactView<StatisticalAnalysisViewControl, StatisticalAnalysisViewState> {
    componentWillMount() {
        // 初始化数据源
        this.setState({
            company_model_line_data: [],
            category_model_line_data: [],
            single_product_model_line_data: [],
            external_links_model_line_data: [],
            total_analysis_line: [],
            ranking_list_data: [],
            statistics_data: {},
            loading: false
        });
    }
    componentDidMount() {
        const currentCompanySign = IndustryInternetSignAppStorage.getCurrentCompanySign(),
            currentAccountPermission = IndustryInternetSignAppStorage.getCurrentUserRoles();
        console.log('currentCompanySign', currentCompanySign);
        console.log('currentAccountPermission', currentAccountPermission);
        let currentAdminPermission = false, currentCompanyPermission = false;
        for (const role of currentAccountPermission) {
            for (const permission of role.permission) {
                if (permission.permission === PermissionList.CompanyTemplate_Select_Admin.permission &&
                    permission.permission_state === PermissionState.grant) {
                    currentAdminPermission = true;
                }
                if (permission.permission === PermissionList.CompanyTemplate_Select_Company.permission &&
                    permission.permission_state === PermissionState.grant) {
                    currentCompanyPermission = true;
                }
            }
        }
        if (currentAdminPermission) {
            this.setState({
                loading: true
            });
            this.handleAnalysis()
                .then(() => {
                    this.setState({
                        loading: false
                    });
                })
                .catch(error => {
                    this.setState({
                        loading: false
                    });
                    log("StatisticalAnalysisViewControl", error.message);
                });
            return;
        } else {
            if (currentCompanyPermission && currentCompanySign) {
                this.props.history!.push(`${this.props.current_company_sign_path}/${currentCompanySign!.id}`);
            } else {
                notification.open({
                    message: '提示',
                    description: '请联系管理员绑定企业',
                    onClick: () => {
                        console.log('Notification Clicked!');
                    },
                });
                this.props.history!.push(ROUTE_PATH.securitySettings);
            }
        }
    }
    async handleAnalysis() {
        const company_model_line_data = await this.analysisStatisticsService!()!.line_data!('company')!;
        const category_model_line_data = await this.analysisStatisticsService!()!.line_data!('category')!;
        const single_product_model_line_data = await this.analysisStatisticsService!()!.line_data!('single_product')!;
        const external_links_model_line_data = await this.analysisStatisticsService!()!.line_data!('external_links')!;
        const total_analysis_line = await this.analysisStatisticsService!()!.total_analysis_bar!()!;
        // const ranking_list_data = await this.analysisStatisticsService!()!.AnalysStatistics!('company')!;
        const statistics_data = {
            company_model_total: company_model_line_data!.model_total,
            company_model_month_add: company_model_line_data!.model_month_add,
            category_model_total: category_model_line_data!.model_total,
            category_model_month_add: category_model_line_data!.model_month_add,
            single_product_model_total: single_product_model_line_data!.model_total,
            single_product_model_month_add: single_product_model_line_data!.model_month_add,
            external_links_model_total: external_links_model_line_data!.model_total,
            external_links_model_month_add: external_links_model_line_data!.model_month_add,
            analysis_total: total_analysis_line!.model_total,
            analysis_add: total_analysis_line!.model_month_add
        };
        this.setState({
            statistics_data: statistics_data,
            company_model_line_data: company_model_line_data!.result,
            category_model_line_data: category_model_line_data!.result,
            single_product_model_line_data: single_product_model_line_data!.result,
            external_links_model_line_data: external_links_model_line_data!.result,
            total_analysis_line: total_analysis_line!.result,
            // ranking_list_data: ranking_list_data!,
        });
    }
    // 初始化服务
    analysisStatisticsService?() {
        return getObject(this.props.analysisStatisticsService_Fac!);
    }
    // 模板按钮选择事件
    modelButtonSelect = (value: any) => {
        this.analysisStatisticsService!()!.AnalysStatistics!(value[0])!
            .then((data: AnalysisStatistics[]) => {
                this.setState({
                    ranking_list_data: data
                });
            })
            .catch(error => {
                // debugger;
                console.log(error);
            });
    }
    render() {
        const redeirect = isPermission ? isPermission!(PermissionList.StatisticalAnalysis_Select) : undefined;
        if (redeirect) {
            return redeirect;
        }
        const ismoblie = this.state.isMobile;
        let statistics_data = this.state.statistics_data;
        const antIcon = <Icon type="loading" style={{ fontSize: 24 }} spin={true} />;
        return !ismoblie ?
            (
                <Spin spinning={this.state.loading ? this.state.loading : false} indicator={antIcon} >
                    <StatisticalAnalysisLayout
                        card_top_title_one='企业模板标识总数'
                        card_top_content_one={(statistics_data!.company_model_total ? statistics_data!.company_model_total : 0) + '个'}
                        card_foot_title_one='当月新增量'
                        card_foot_content_one={(statistics_data!.company_model_month_add ? statistics_data!.company_model_month_add : 0) + ''}
                        card_top_title_two='品类模板标识总数'
                        card_top_content_two={(statistics_data!.category_model_total ? statistics_data!.category_model_total : 0) + '个'}
                        card_foot_title_two='当月新增量'
                        card_foot_content_two={(statistics_data!.category_model_month_add ? statistics_data!.category_model_month_add : 0) + ''}
                        card_top_title_three='单品模板标识总数'
                        card_top_content_three={(statistics_data!.single_product_model_total ? statistics_data!.single_product_model_total : 0) + '个'}
                        card_foot_title_three='当月新增量'
                        card_foot_content_three={(statistics_data!.single_product_model_month_add ? statistics_data!.single_product_model_month_add : 0) + ''}
                        card_top_title_four='外链模板标识总数'
                        card_top_content_four={(statistics_data!.external_links_model_total ? statistics_data!.external_links_model_total : 0) + '个'}
                        card_foot_title_four='当月新增量'
                        card_foot_content_four={(statistics_data!.external_links_model_month_add ? statistics_data!.external_links_model_month_add : 0) + ''}
                        chart_top_content={(statistics_data!.analysis_total ? statistics_data!.analysis_total : 0) + '次'}
                        chart_title='当月新增量'
                        chart_content={(statistics_data!.analysis_add ? statistics_data!.analysis_add : 0) + ''}
                    >
                        <EchartsReact
                            echart_id='company_model_line'
                            data={this.state.company_model_line_data!}
                            option={lineOption}
                            map_type='line'
                            x_field_name='date'
                            y_field_name='count'
                        />
                        <EchartsReact
                            echart_id='category_model_line'
                            data={this.state.category_model_line_data!}
                            option={lineOption}
                            map_type='line'
                            x_field_name='date'
                            y_field_name='count'
                        />
                        <EchartsReact
                            echart_id='single_product_model_line'
                            data={this.state.single_product_model_line_data!}
                            option={lineOption}
                            map_type='line'
                            x_field_name='date'
                            y_field_name='count'
                        />
                        <EchartsReact
                            echart_id='external_links_model_line'
                            data={this.state.external_links_model_line_data!}
                            option={lineOption}
                            map_type='line'
                            x_field_name='date'
                            y_field_name='count'
                        />
                        <EchartsReact
                            echart_id='total_analysis_line'
                            data={this.state.total_analysis_line!}
                            option={barOption}
                            map_type='bar'
                            x_field_name='date'
                            y_field_name='count'
                        />
                        <NTButtonSelect onChange={this.modelButtonSelect} is_single={true} default_value={['company']} >
                            <NTButtonOption text='企业标识' value='company' />
                            <NTButtonOption text='品类标识' value='category' />
                            <NTButtonOption text='单品标识' value='single_product' />
                            <NTButtonOption text='跳转标识' value='external_links' />
                        </NTButtonSelect>
                        <NTOperationTable
                            bordered={false}
                            data_source={this.state.ranking_list_data}
                            columns_data_source={columns_data_source}
                            table_size='middle'
                            showHeader={true}
                            is_pagination={false}
                            rowKey='id'
                        />
                        <Tooltip title="该图表为每月标识新增量趋势图（x轴为月份，y轴为个数）">
                            <CommonIcon icon='antd@info-circle' />
                        </Tooltip>
                        <Tooltip title="该图表为每月标识新增量趋势图（x轴为月份，y轴为个数）">
                            <CommonIcon icon='antd@info-circle' />
                        </Tooltip>
                        <Tooltip title="该图表为每月标识新增量趋势图（x轴为月份，y轴为个数）">
                            <CommonIcon icon='antd@info-circle' />
                        </Tooltip>
                        <Tooltip placement="right" title="该图表为每月标识新增量趋势图（x轴为月份，y轴为个数）">
                            <CommonIcon icon='antd@info-circle' />
                        </Tooltip>
                    </StatisticalAnalysisLayout>
                </Spin>
            ) : (<div />);
    }
}

/**
 * 控件：统计分析视图控件控制器
 * @description 控制统计分析视图控件
 * @author yzy
 */
@addon('StatisticalAnalysisView', '统计分析视图控件', '控制统计分析视图控件')
@reactControl(StatisticalAnalysisView, true)
export class StatisticalAnalysisViewControl extends ReactViewControl {
    /**
     * 解析统计服务
     */
    public analysisStatisticsService_Fac?: Ref<IAnalysisStatisticsService>;
    /** 当前企业标识详情页Path */
    public current_company_sign_path?: string;
}